package controllers

import (
	"github.com/gin-gonic/gin"
	"shoping.zozoo.net/model"
	"shoping.zozoo.net/params"
	"shoping.zozoo.net/service"
	"shoping.zozoo.net/tool"
)

type UserController struct {
	service service.UserInterface
}

//创建用户控制器实例
func NewUserController(s service.UserInterface) *UserController {
	return &UserController{
		s,
	}
}

//用户注册
func (u *UserController) Register(c *gin.Context) {
	var (
		param *params.UserParam
		err   error
		id    int64
	)

	param = new(params.UserParam)

	//模型绑定
	if err = c.ShouldBindJSON(param); err != nil {
		tool.ResponseError(c, tool.Fail, err.Error())
		return
	}

	//判断数据是否插入成功
	if id, err = u.service.Create(param); err != nil {
		tool.ResponseError(c, tool.Fail, err.Error())
		return
	}

	tool.ResponseSuccess(c, id)
}

//用户登录
func (u *UserController) Login(c *gin.Context) {
	var (
		param *params.UserLogin
		err   error
		user  *model.User
		token string
	)

	param = new(params.UserLogin)

	//模型绑定
	if err = c.ShouldBindJSON(param); err != nil {
		tool.ResponseError(c, tool.Fail, err.Error())
		return
	}

	user = new(model.User)
	if user, err = u.service.Login(param); err != nil {
		tool.ResponseError(c, tool.Fail, err.Error())
		return
	}

	if token,err = tool.GenerateToken(user.Id);err != nil {
		tool.ResponseError(c, tool.Fail, err.Error())
		return
	}

	tool.ResponseSuccess(c, token)
}
